package com.seio.edc.controller.business;

import com.nova.edc.model.energy.Energy;
import com.nova.edc.model.energy.Gather;
import com.nova.edc.model.system.*;
import com.nova.edc.service.collect.StatusService;
import com.nova.edc.service.energy.*;
import com.nova.edc.service.system.*;
import com.nova.frame.dao.pager.Page;
import com.nova.frame.dao.pager.PageList;
import com.nova.frame.utils.JdbcUtils;
import com.seio.edc.common.Constants;
import com.seio.edc.util.AssitDateUtil;
import com.seio.edc.util.DateTimeUtil;
import com.seio.edc.util.DateUtil;
import com.seio.edc.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * 经济效益
 *
 * @author Administrator
 */
@Controller
@RequestMapping(value = "/economicBenefit")
public class EconomicBenefitContoller {
    private static Logger log = Logger
            .getLogger(EconomicBenefitContoller.class);
    @Autowired
    private CollectAreaItemAirService novaCollectAreaItemAirService;

    @Autowired
    private CollectAreaService novaCollectAreaService;

    @Autowired
    private EnergyService novaEnergyService;

    @Autowired
    private ElecPriceService novaElecPriceService;

    @Autowired
    private CustomerInfoService novaCustomerInfoService;

    @Autowired
    private AreaPointService areaPointService;

    @Autowired
    private CustomerAreaService customerAreaService;

    @Autowired
    private StatusService statusService;

    @Autowired
    private DeviceTypeService deviceTypeService;

    @Autowired
    private GatherService novaGatherService;

    @Autowired
    private AreaPointService novaAreaPointService;

    @Autowired
    private OverallStatisticsService novaOverallStatisticsService;

    @Autowired
    private GatherSummaryService novaGatherSummaryService;

    private static final int PAGE_SIZE = 10;

    @InitBinder("ebEntity")
    public void initBinder1(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("ebEntity.");
    }

    /**
     * 数据采集初期页面
     */
    @RequestMapping(value = "EconomicBenefitFth")
    public ModelAndView EconomicBenefitFth(HttpServletRequest request,
                                           ModelMap modelMap, Integer pageIndex, Integer areaId, AreaPoint areaPoint, Integer devicetype,
                                           String startTime, String endTime) {
        log.info("数据采集开始："
                + DateTimeUtil.getNowTime(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));

        CustomerArea customerArea = customerAreaService.findById(areaId);
        Integer customerinfoid = customerArea.getCustomerinfoid();
        modelMap.put("customerArea", customerArea);
        // 当前页数
        Page page = new Page();
        page.setCurrentPage(pageIndex == null || pageIndex == 0 ? 1 : pageIndex);
        page.setPageSize(PAGE_SIZE);
        modelMap.put("pageIndex", page.getCurrentPage());
        areaPoint.setAreaid(areaId);
        if (com.nova.frame.utils.StringUtils.isNotNullOrEmpty(areaPoint
                .getGatewayid())) {
            areaPoint.setGatewayid(areaPoint.getGatewayid().trim());
        }
        if (areaPoint.getSensorid() != null && areaPoint.getSensorid() != 0) {
            areaPoint.setSensorid(areaPoint.getSensorid());
        }
        if (devicetype != null && ModelConstant.AIR_AIRTYPE == devicetype) {
            areaPoint.setDevicetypeid(deviceTypeService.getByName(ModelConstant.DEVICE_AIR).getId());
        } else {
            areaPoint.setDevicetypeid(deviceTypeService.getByName(ModelConstant.DEVICE_LIGHTENERGY).getId());
        }
        PageList<AreaPoint> pageList = areaPointService.findAreaPointPageList(areaPoint, page, "GatewayID, SensorID, ChannelID", "ASC");
        modelMap.put("areaPoint", areaPoint);
        modelMap.put("dataCount", page.getRowCount());
        modelMap.put("pageCount", page.getTotalPage());

        // 数据列表
        List<AreaPoint> areaPoints = pageList.getDatas();

        if (StringUtils.isBlank(startTime) || StringUtils.isEmpty(startTime)) {
            startTime = DateUtil.today() + " 00:00:00";
        }
        if (StringUtils.isBlank(endTime) || StringUtils.isEmpty(endTime)) {
            endTime = DateUtil.today() + " 23:59:59";
        }

        JdbcUtils.changeDataSource(Constants.COLLECT_DB);
        for (AreaPoint point : areaPoints) {
            List<Gather> oneToday = novaGatherService.findOneToday(startTime, endTime, point, ModelConstant.LIGHT_ON);
//            novaAreaPointService.findStatu(point);
            int summaryTime = 0;
            for (Gather gather : oneToday) {
                if (gather.getActivestate() == ModelConstant.LIGHT_ON) {
                    summaryTime = summaryTime + gather.getActivetime();
                }
            }
            point.setUseminute(summaryTime);
//            if (point.getStatus()!=null&&point.getStatus()== ModelConstant.LIGHT_ON) {
//                point.setStatusName("正常工作");
//            }else {
//                point.setStatusName("未工作");
//            }
            statusService.wrapAreaPoint(point);
        }
        JdbcUtils.changeDataSource(Constants.DEFAULT_DB);
//        novaEnergyService.updateLightUseHour(areaPoints, areaId, startTime,
//                endTime);

        modelMap.put("listdata", areaPoints);
        // 获取客户总计的耗电功率
//        Map<String, BigDecimal> allEnergy = novaEnergyService
//                .getDetailEnergyByCompany(areaId, startTime, endTime);
//        modelMap.put("allEnergy", allEnergy);
        CustomerInfo customerInfo = novaCustomerInfoService.getById(customerinfoid);
//        modelMap.put("customername",
//                novaCustomerInfoService.getById(customerinfoid)
//                        .getCustomername());
        modelMap.put("customerInfo", customerInfo);
        modelMap.put("startTime", startTime);
        modelMap.put("endTime", endTime);
        log.info("数据采集结束："
                + DateTimeUtil.getNowTime(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));
        return new ModelAndView("business/economicbenefit", modelMap);
    }

    /**
     * 空调数据采集初期页面
     */
    @RequestMapping(value = "AirEconomicBenefitFth")
    public ModelAndView AirEconomicBenefitFth(HttpServletRequest request,
                                              ModelMap modelMap, Integer pageIndex,
                                              CollectAreaItemAir collectAreaItemAir, String startTime,
                                              String endTime) {
        log.info("数据采集开始："
                + DateTimeUtil.getNowTime(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));
        // 当前页数
        modelMap.put("companycode", collectAreaItemAir.getCompanycode());
        modelMap.put("customername",
                novaCustomerInfoService.getByCompanyCode(collectAreaItemAir.getCompanycode())
                        .getCustomername());
        Page page = new Page();
        page.setCurrentPage(pageIndex == null || pageIndex == 0 ? 1 : pageIndex);
        page.setPageSize(PAGE_SIZE);
        modelMap.put("pageIndex", page.getCurrentPage());
        collectAreaItemAir.setCompanycode(collectAreaItemAir.getCompanycode());
        if (com.nova.frame.utils.StringUtils
                .isNotNullOrEmpty(collectAreaItemAir.getGatewayid())) {
            collectAreaItemAir.setGatewayid(collectAreaItemAir.getGatewayid()
                    .trim());
        }
        if (collectAreaItemAir.getSensorid() != null) {
            collectAreaItemAir.setSensorid(collectAreaItemAir.getSensorid());
        }
        PageList<CollectAreaItemAir> pageList = novaCollectAreaItemAirService
                .findbyCompany(collectAreaItemAir, page,
                        "gatewayid,SensorID,ChannelID", "asc");
        modelMap.put("collectAreaItem", collectAreaItemAir);
        modelMap.put("dataCount", page.getRowCount());
        modelMap.put("pageCount", page.getTotalPage());

        // 数据列表
        List<CollectAreaItemAir> areaItemsair = pageList.getDatas();
        if (StringUtils.isBlank(startTime) || StringUtils.isEmpty(startTime)) {
            startTime = DateUtil.today() + " 00:00:00";
        }
        if (StringUtils.isBlank(endTime) || StringUtils.isEmpty(endTime)) {
            endTime = DateUtil.today() + " 23:59:59";
        }
        int alluseminute = novaEnergyService.updateAirUseHour(areaItemsair,
                collectAreaItemAir.getCompanycode(), startTime, endTime);
        modelMap.put("airlistdata", areaItemsair);
        // 每页总时间
        int pageuseminute = 0;
        for (CollectAreaItemAir ele : areaItemsair) {
            pageuseminute += ele.getUseminute();
        }
        if (areaItemsair.size() > 0) {
            modelMap.put("alluseminute", alluseminute);
            modelMap.put("pageuseminute", pageuseminute);
        }
        modelMap.put("startTime", startTime);
        modelMap.put("endTime", endTime);
        log.info("数据采集结束："
                + DateTimeUtil.getNowTime(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));
        return new ModelAndView("airdata/aireconomicbenefit", modelMap);
    }

    /**
     * 设备状态初期页面
     */
    @RequestMapping(value = "devicestatus")
    public ModelAndView deviceStatus(HttpServletRequest request,
                                     ModelMap modelMap, Integer pageIndex, Integer companycode,
                                     String sidx, String sord, AreaPoint areaPoint) {
        // 当前页数
        Page page = new Page();
        page.setCurrentPage(pageIndex == null || pageIndex == 0 ? 1 : pageIndex);
        page.setPageSize(PAGE_SIZE);
        modelMap.put("pageIndex", page.getCurrentPage());
        Integer id = novaCustomerInfoService.getByCompanyCode(companycode).getId();
        areaPoint.setCustomerinfoid(id);
        areaPoint.setDevicetypeid(deviceTypeService.getByName(ModelConstant.DEVICE_LIGHTENERGY).getId());
        if (com.nova.frame.utils.StringUtils.isNullOrEmpty(sidx)) {
            sidx = "gatewayid,SensorID,ChannelID";
        }
        if (com.nova.frame.utils.StringUtils.isNullOrEmpty(sord)) {
            sord = "asc";
        }
        List<AreaPoint> areaPoints = areaPointService.findPageAreaPointStatus(areaPoint, companycode, DateUtil.today(), page, sidx, sord);
        modelMap.put("sidx", sidx);
        modelMap.put("areaPoint", areaPoint);
        modelMap.put("areaPoints", areaPoints);
        modelMap.put("dataCount", page.getRowCount());
        modelMap.put("pageCount", page.getTotalPage());
        CustomerInfo customerInfo = novaCustomerInfoService.getByCompanyCode(companycode);
        modelMap.put("customerInfo", customerInfo);
        modelMap.put("companycode", companycode);
        modelMap.put("customername",
                novaCustomerInfoService.getByCompanyCode(companycode)
                        .getCustomername());
        return new ModelAndView("business/devicestatus", modelMap);
    }

    /**
     * 空调设备状态初期页面
     */
    @RequestMapping(value = "airdevicestatus")
    public ModelAndView airdeviceStatus(HttpServletRequest request,
                                        ModelMap modelMap, Integer pageIndex,
                                        String sidx, String sord, CollectArea collectArea) {
        // 当前页数
        Page page = new Page();
        page.setCurrentPage(pageIndex == null || pageIndex == 0 ? 1 : pageIndex);
        page.setPageSize(PAGE_SIZE);
        modelMap.put("pageIndex", page.getCurrentPage());
        collectArea.setCompanycode(collectArea.getCompanycode());
        collectArea.setDevicetype(419);
        if (com.nova.frame.utils.StringUtils.isNullOrEmpty(sidx)) {
            sidx = "gatewayid,SensorID,ChannelID";
        }
        if (com.nova.frame.utils.StringUtils.isNullOrEmpty(sord)) {
            sord = "asc";
        }
        List<CollectArea> collectAreasairs = novaCollectAreaService
                .findPageCollectAreaStatus(collectArea, DateUtil.today(), page,
                        sidx, sord);
        modelMap.put("sidx", sidx);
        modelMap.put("collectArea", collectArea);
        modelMap.put("collectAreasairs", collectAreasairs);
        modelMap.put("dataCount", page.getRowCount());
        modelMap.put("pageCount", page.getTotalPage());
        modelMap.put("companycode", collectArea.getCompanycode());
        modelMap.put("customername",
                novaCustomerInfoService.getByCompanyCode(collectArea.getCompanycode())
                        .getCustomername());

        return new ModelAndView("airdata/airdevicestatus", modelMap);
    }


    /**
     * 经济效益表2初期页面
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "EconomicBenefitscd")
    public ModelAndView EconomicBenefitscd(HttpServletRequest request,
                                           ModelMap modelMap, String startDate, String endDate,
                                           Integer companycode) {

        log.info("经济效益开始："
                + DateTimeUtil.getNowTime(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));

        /*********** 时间条件查询-end **************/

        if (StringUtil.isEmpty(startDate)) {
            // startDate = DateUtil.getAddDate("DATE", -7,
            // DateUtil.DEFAULT_DATE_FORMAT);
            startDate = ModelConstant.MIN_DATE;
        }

        if (StringUtil.isEmpty(endDate)) {
            endDate = DateUtil.today();
        }
        CustomerInfo customerInfo = novaCustomerInfoService.getByCompanyCode(companycode);
        Energy energy = novaGatherSummaryService.getEnergyByCompany(customerInfo.getId(),
                startDate, endDate);
        List<ElecPrice> elecPrices = novaElecPriceService
                .findElecPriceByCompanyCode(companycode);
        modelMap.put("elecPrices", elecPrices);
        if (elecPrices != null && elecPrices.size() > 0) {
            modelMap.put("elecPrice", elecPrices.get(0));
        } else {
            ElecPrice elecPrice = new ElecPrice();
            elecPrice.setUnitprice(BigDecimal.ZERO);
            modelMap.put("elecPrice", elecPrice);
        }
        modelMap.put("energy", energy);
        modelMap.put("startDate", startDate);
        modelMap.put("endDate", endDate);
        Integer propertion = 0;
        try {
            if (customerInfo.getMoneysavetarget() != null) {
                propertion = energy.getSaveCost().divide(customerInfo.getMoneysavetarget(), 2, BigDecimal.ROUND_CEILING).multiply(new BigDecimal(50)).intValue();
            } else {
                propertion = 0;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        modelMap.put("propertion", propertion > 50 ? 50 : propertion);
        modelMap.put("customerInfo", customerInfo);
        modelMap.put("companycode", companycode);
        modelMap.put("customername",
                novaCustomerInfoService.getByCompanyCode(companycode)
                        .getCustomername());
        log.info("经济效益结束："
                + DateTimeUtil.getNowTime(DateTimeUtil.YYYY_MM_DD_HH_MM_SS));
        return new ModelAndView("business/economicbenefit_sec", modelMap);
    }

    // 获取某个单位一段时间内每个区域的耗电量
    @RequestMapping(value = "showDetail.shtml")
    public ModelAndView showDetail(HttpServletRequest request,
                                   ModelMap modelMap, HttpSession session, String gatewayid,
                                   Integer sensorid, Integer channelid, String startTime,
                                   String endTime) {
        AreaPoint areaPoint = new AreaPoint();
        areaPoint.setGatewayid(gatewayid);
        areaPoint.setSensorid(sensorid);
        areaPoint.setChannelid(channelid);
        JdbcUtils.changeDataSource(Constants.COLLECT_DB);
        List<Gather> gatherList = novaGatherService.findOneToday(startTime, endTime, areaPoint, ModelConstant.LIGHT_ON);
        JdbcUtils.changeDataSource(Constants.DEFAULT_DB);
        ArrayList<Gather> gathers = new ArrayList<Gather>();
        for (int i = 0; i < gatherList.size(); i++) {
            Gather gather = new Gather();
            if (gatherList.get(i).getActivestate() == 1) {
                gather.setActivetime(gatherList.get(i).getActivetime());
                if (i == gatherList.size() - 1) {
                    gather.setSpantime(DateUtil.toString(
                            gatherList.get(i).getStartdate(), "HH:mm")
                            + " ~ "
                            + "24:00");
                } else {
                    gather.setSpantime(DateUtil.toString(
                            gatherList.get(i).getStartdate(), "HH:mm")
                            + " ~ "
                            + DateUtil.toString(
                            gatherList.get(i + 1).getStartdate(), "HH:mm"));
                }
                gathers.add(gather);
            }
        }
//        List<CollectData> list = collectDataService
//                .findDataDetail(gatewayid, sensorid, channelid, startTime,
//                        endTime, ModelConstant.LIGHT_ON);
//        // 获取所有的开关灯的时间节点
//        List<CollectData> detail = new ArrayList<CollectData>();
//        if (list.size() != 0 && list != null) {
//            Date temp = list.get(0).getActivetime();
//            detail.add(list.get(0));
//            for (int i = 0; i < list.size(); i++) {
//                CollectData collectData = list.get(i);
//                if (!AssitDateUtil.dateInField(temp,
//                        collectData.getActivetime())) {
//                    detail.add(list.get(i - 1));
//                    detail.add(list.get(i));
//                }
//                if (i == list.size() - 1 && detail.size() % 2 == 1) {
//                    detail.add(list.get(i));
//                }
//                temp = AssitDateUtil.getAddMinute(collectData.getActivetime(),
//                        collectData.getActivecount());
//            }
//        }
        // 所有的时间节点转化为可以显示的格式
//        List<CollectDataDetail> details = new ArrayList<CollectDataDetail>();
//        if (detail != null && detail.size() != 0) {
//            for (int i = 0; i < detail.size(); i = i + 2) {
//                CollectDataDetail collectDataDetail = new CollectDataDetail();
//                Date startTime2 = detail.get(i).getActivetime();
//                Date endTime2 = AssitDateUtil.getAddMinute(detail.get(i + 1)
//                        .getActivetime(), detail.get(i + 1).getActivecount());
//                collectDataDetail.setStartTime(startTime2);
//                collectDataDetail.setEndTime(endTime2);
//                collectDataDetail.setAmount(AssitDateUtil.getSpanMinute(
//                        startTime2, endTime2));
//                collectDataDetail
//                        .setSpanTime(DateUtil.toString(startTime2, "HH:mm")
//                                + " ~ " + DateUtil.toString(endTime2, "HH:mm"));
//                details.add(collectDataDetail);
//            }
//        }
        modelMap.put("gathers", gathers);
        modelMap.put("gatewayid", gatewayid);
        modelMap.put("sensorid", sensorid);
        modelMap.put("channelid", channelid);
        modelMap.put("startTime", startTime);
        modelMap.put("endTime", endTime);
        return new ModelAndView("business/showdetail", modelMap);
    }

    // 显示每小时显示的亮灯时间
    @RequestMapping(value = "everyHour")
    @ResponseBody
    public List<Gather> everyHour(HttpServletRequest request,
                                  ModelMap modelMap, HttpSession session, String gatewayid,
                                  Integer sensorid, Integer channelid, String startTime,
                                  String endTime) {
        JdbcUtils.changeDataSource(Constants.COLLECT_DB);
        List<Gather> gatherList = novaGatherService.findEveryHour(gatewayid, sensorid, channelid, startTime, endTime);
        JdbcUtils.changeDataSource(Constants.DEFAULT_DB);
        for (Gather gather : gatherList) {
            if (gather.getActivetime() > 56) {
                gather.setActivetime(60);
            }
            gather.setSpantime(DateUtil.toString(
                    gather.getStartdate(), "HH:mm")
                    + " ~ "
                    + DateUtil.toString(
                    AssitDateUtil.getAddHour(
                            gather.getStartdate(), 1),
                    "HH:mm"));
        }
        return gatherList;
    }

    // 显示图片
    @RequestMapping(value = "showPicture")
    @ResponseBody
    public Map<String, Object> showPicture(HttpServletRequest request,
                                           ModelMap modelMap, @RequestBody String params) {
        HashMap<String, Object> map = new HashMap<String, Object>();// 定义返回MAP
        map.put("fileName", "");
        return map;
    }

}
